package com.example.xymarket.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.xymarket.adapter.ShopAdapter;
import com.example.xymarket.common.Info;
import com.example.xymarket.myView.MyDialog;
import com.example.xymarket.myView.StatusBar;
import com.example.xymarket.R;
import com.example.xymarket.httpUtil.ImageService;
import com.example.xymarket.po.Goods;
import com.example.xymarket.httpUtil.GoodsService;
import com.example.xymarket.common.MyFile;
import com.example.xymarket.common.MyHandler;

import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyShopActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_shop);
        initMyShop();
        MyHandler myHandler=new MyHandler(getApplicationContext(),handler);
        GoodsService goodsService=new GoodsService(myHandler);
        StatusBar.setStatusBarColor(this,StatusBar.yellow);
        goodsService.getGoodsByMerchant(Info.getMyMerchant().getId());
    }

    public void initMyShop()
    {
        TextView textView=(TextView)findViewById(R.id. shop_name ) ;
        textView.setText(Info.getMyMerchant().getName());
        TextView textView2=(TextView)findViewById(R.id. description);
        textView2.setText(Info.getMyMerchant().getDescription());
        ImageView imageView=(ImageView)findViewById(R.id.shop_avatar);
        imageView.setImageDrawable(Info.getMyMerchant().getDrawable());
    }

    private Map<String,Object> map;
    public void updateListView(List<Goods> list)
    {
        if(list==null)return;
        ListView listView = (ListView) findViewById(R.id.goods_listView);
        try {
            ShopAdapter adapter = new ShopAdapter(list,this,handler);
            listView.setAdapter(adapter);
        }
        catch (Exception e)
        {
            System.out.println(e.toString());
        }
    }


    @SuppressLint("HandlerLeak")
    final Handler handler = new Handler()
    {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1) {
                updateListView((List<Goods>) msg.obj);
            }

            if(msg.what==2) {
                String uri=(String) msg.obj;
                updateGoods(uri);
            }
            if(msg.what==-2) {
                Toast.makeText(getApplicationContext(),"图片上传失败",Toast.LENGTH_LONG).show();
            }
            if(msg.what==100) {
                Toast.makeText(getApplicationContext(),"修改完毕",Toast.LENGTH_LONG).show();
                GoodsService goodsService=new GoodsService(myHandler);
                goodsService.getGoodsByMerchant(1);
            }
            if(msg.what==-100) {
                Toast.makeText(getApplicationContext(),"修改失败",Toast.LENGTH_LONG).show();

            }
            if(msg.what==3) {
                map=(Map<String,Object>)msg.obj;
                initDialog();
            }
        }
    };

    MyHandler myHandler=new MyHandler(this,handler);
    public void initDialog()
    {
        myDialog1=new MyDialog(MyShopActivity.this,map);
        myDialog1.show();
        myDialog1.setOnCenterItemClickListener(new MyDialog.OnCenterItemClickListener() {
            @Override
            public void OnCenterItemClick(MyDialog dialog, View view) {
                switch (view.getId())
                {
                    case R.id.OK:
                    {
                        ImageService imageService=new ImageService(myHandler);
                        imageService.uploadImage(MyFile.getFile((Bitmap)map.get("imageView")));
                        break;
                    }
                    case R.id.cancle:
                    {
                        myDialog1.dismiss();
                        break;
                    }
                    case R.id.chose_image:
                    {
                        Intent intent = new Intent(Intent.ACTION_PICK, null);
                        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                        startActivityForResult(intent, 2);
                        break;
                    }
                }

            }
        });
    }

    void updateGoods(String uri)
    {
        Map<String, Object> newMap = new HashMap<>();
        newMap.put("image",uri);
        newMap.put("id",(Integer)map.get("id"));
        newMap.put("title",myDialog1.getTitle_input().getText().toString());
        newMap.put("stockQty",Integer.parseInt(myDialog1.getNum_input().getText().toString()));
        newMap.put("price",Integer.parseInt(myDialog1.getPrice_input().getText().toString()));
        int i = myDialog1.getSpinner().getSelectedItemPosition();
        newMap.put("categoryId", i + 1);
        GoodsService goodsService = new GoodsService(myHandler);
        goodsService.InsertGoods(newMap);
    }

    private MyDialog myDialog1;
    /**
     * 自定义dialog2 简单自定义布局
     */

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2) {
            // 从相册返回的数据
            Log.e(this.getClass().getName(), "Result:" + data.toString());
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                Bitmap bitmap = null;
                try {
                    bitmap = BitmapFactory.decodeStream(this.getContentResolver().openInputStream(uri));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                myDialog1.setImageView(bitmap);
                map.put("imageView",bitmap);

            }
        }
    }


    /**
     * 返回我的
     * @param view
     */
    public void toMine(View view)
    {
        Intent intent = new Intent(getApplicationContext(), MineActivity.class);
        startActivity(intent);overridePendingTransition(0, 0);
    }


    public void InsertNewGoods(View view)
    {
        Intent intent = new Intent(getApplicationContext(), InsertGoodsActivity.class);
        startActivity(intent);overridePendingTransition(0, 0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            Intent intent = new Intent(getApplicationContext(), MineActivity.class);
            startActivity(intent);overridePendingTransition(0, 0);
        }
        return super.onKeyDown(keyCode, event);
    }
}